from django.core.paginator import Paginator
from django.db.models import ProtectedError
from django.http import JsonResponse
import time

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from diaodumanage.models import Scrw, WorkPlan, Watchkeeper, EmphasisWork
from usermanage.models import GongQu, User, SelectCollection, CheJian


@csrf_exempt
def addWorkPlan(request):
    # 区间
    qujian = request.POST['qujian']
    # 日期
    date = request.POST['date']
    # 时间
    time2 = request.POST['time2']
    time1 = request.POST['time1']
    # 内容
    context = request.POST['context']
    # 负责人
    people = request.POST['people']
    # 施工类型和维修类型
    type = request.POST['type']
    # 工区
    gongQuId = request.POST['gongQuId']
    cheJianId = request.POST['cheJianId']
    # 工作类型
    workType = request.POST['workType']
    workPlan = WorkPlan.objects.create(
        qujian=qujian,
        date=date,
        time1=time1,
        time2=time2,
        context=context,
        people=people,
        type=type,
        gong_qu_id=gongQuId,
        work_type=workType,
        che_jian_id=cheJianId)
    workPlan.save()

    if workPlan.id is None:
        return JsonResponse({'code': 500, 'message': '添加失败'})
    return JsonResponse({'code': 200, 'message': '添加成功'})


# 添加生产任务
@csrf_exempt
def addScrw(request):
    gongQuId = request.POST['gongQuId']
    cheJianId = request.POST['cheJianId']
    xianMingId = request.POST['xianMingId']
    date = request.POST['date']
    workTypeId = request.POST['workTypeId']
    piZhunDate = request.POST['piZhunDate']
    geiDianDate = request.POST['geiDianDate']
    zuoYeDate = request.POST['zuoYeDate']
    fzrId = request.POST['fzrId']
    fhyId = request.POST['fhyId']
    llyId = request.POST['llyId']
    scxm = request.POST['scxm']
    wcqk = request.POST['wcqk']
    gznr = request.POST['gznr']
    czwt = request.POST['czwt']
    snzy = request.POST['snzy']
    scrw = Scrw.objects.create(
        gong_qu_id=gongQuId,
        che_jian_id=cheJianId,
        xian_ming_id=xianMingId,
        date=date,
        work_type_id=workTypeId,
        pi_zhun_date=piZhunDate,
        gei_dian_date=geiDianDate,
        zuo_ye_date=zuoYeDate,
        fzr_id=fzrId,
        fhy_id=fhyId,
        lly_id=llyId,
        scxm=scxm,
        wcqk=wcqk,
        gznr=gznr,
        czwt=czwt,
        snzy=snzy
    )
    if scrw.id is None:
        return JsonResponse({'code': 500, 'message': '添加失败'})
    return JsonResponse({'code': 200, 'message': '添加成功'})


def getScrw(request):
    scrw = Scrw.objects.get(id=request.GET['id'])
    scrwJson = {
        'id': scrw.id,
        'gongQuId': scrw.gong_qu_id,
        'cheJianId': scrw.che_jian_id,
        'xianMingId': scrw.xian_ming_id,
        'date': scrw.date,
        'workTypeId': scrw.work_type_id,
        'piZhunDate': scrw.pi_zhun_date,
        'geiDianDate': scrw.gei_dian_date,
        'zuoYeDate': scrw.zuo_ye_date,
        'fzrId': scrw.fzr_id,
        'fhyId': scrw.fhy_id,
        'llyId': scrw.lly_id,
        'scxm': scrw.scxm,
        'wcqk': scrw.wcqk,
        'gznr': scrw.gznr,
        'czwt': scrw.czwt,
        'snzy': scrw.snzy
    }
    return JsonResponse({'code': 200, 'message': '查询成功', 'data': scrwJson})


@csrf_exempt
def pageScrw(request):
    limit = request.GET['limit']
    page = int(request.GET['page'])

    scrws = Scrw.objects.all()
    if 'date' in request.POST and 'gongQuId' in request.POST:
        date = request.POST['date'].split('-', 1)
        gongQuId = request.POST['gongQuId']
        year = date[0]
        month = date[1]
        scrws = Scrw.objects.filter(date__year=year, date__month=month).filter(gong_qu_id=gongQuId)
    paginator = Paginator(scrws, limit)  # 分为几页
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    scrwJson = []
    for item in page:
        gongQu = GongQu.objects.values('name', 'che_jian__name').filter(id=item.gong_qu_id).first()
        xianMing = SelectCollection.objects.get(id=item.xian_ming_id)
        fzr = User.objects.get(id=item.fzr_id)
        fhy = User.objects.get(id=item.fhy_id)
        lly = User.objects.get(id=item.lly_id)
        select = {"id": item.id,
                  "gongQu": gongQu['name'],
                  "cheJian": gongQu['che_jian__name'],
                  "xianMing": xianMing.name,
                  "date": item.date,
                  "piZhunDate": item.pi_zhun_date,
                  "zuoYeDate": item.zuo_ye_date,
                  "geiDianDate": item.gei_dian_date,
                  "fzr": fzr.name,
                  "fhy": fhy.name,
                  "lly": lly.name,
                  "scxm": item.scxm,
                  "wcqk": item.wcqk,
                  "gznr": item.gznr,
                  "czwt": item.czwt,
                  "snzy": item.snzy}
        scrwJson.append(select)
    return JsonResponse({"code": 200, "data": {"list": scrwJson}, "length": len(scrws)})


def listWorkPlan(request):
    date = time.strftime("%Y-%m-%d", time.localtime())
    works = WorkPlan.objects.filter(date=date)
    sgjgsJson = []
    wxjhsJson = []
    for item in works:
        cheJian = CheJian.objects.get(id=item.che_jian_id)
        gongQu = GongQu.objects.get(id=item.gong_qu_id)
        itemJson = {
            'qujian': item.qujian,
            'date': item.date,
            'time1': item.time1,
            'time2': item.time2,
            'context': item.context,
            'type': item.type,
            'gongQu': gongQu.name,
            'people': item.people,
            'workType': item.work_type,
            'cheJian': cheJian.name
        }
        if item.work_type == 1:
            sgjgsJson.append(itemJson)
        if item.work_type == 2:
            wxjhsJson.append(itemJson)
    return JsonResponse({"code": 200, "data": {"sgjgsJson": sgjgsJson, "wxjhsJson": wxjhsJson}})


def pageWorkPlan(request):
    page = int(request.GET['page'])
    limit = request.GET['limit']
    works = WorkPlan.objects.all()
    paginator = Paginator(works, limit)  # 分为几页
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    worksJson = []
    for item in page:
        itemJson = {
            'quJian': item.qujian,
            'date': item.date,
            'time1': item.time1,
            'time2': item.time2,
            'context': item.context,
            'type': item.type,
            'gongQuId': item.gong_qu_id,
            'workType': item.work_type,
            'cheJianId': item.che_jian_id,
            'people': item.people
        }
        worksJson.append(itemJson)

    return JsonResponse({"code": 200, "data": {"list": worksJson}, "length": len(works)})


@csrf_exempt
def addWatchkeeper(request):
    id = request.GET["id"]
    watchkeeper = Watchkeeper.objects.filter(user_id=id)
    if len(watchkeeper) > 0:
        return JsonResponse({"code": 500, 'message': '该人员已存在'})
    watchkeeper = Watchkeeper.objects.create(user_id=id)
    if watchkeeper.id is None:
        return JsonResponse({"code": 500, 'message': '添加失败'})
    return JsonResponse({"code": 200, 'message': '添加成功'})


@csrf_exempt
def updateWatchkeeper(request):
    return None


def deleteWatchkeeper(request):
    id = request.GET['id']
    try:
        Watchkeeper.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})
    return JsonResponse({"code": 200, "message": "删除成功"})


def pageWatchkeeper(request):
    limit = request.GET['limit']
    page = int(request.GET['page'])
    watchkeeperList = Watchkeeper.objects.all()
    paginator = Paginator(watchkeeperList, limit)  # 分为几页
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    watchkeepersJson = []
    for item in page:
        user = User.objects.get(id=item.user_id)
        gong = GongQu.objects.filter(id=int(user.gong_qu_id)).values(
            'id',
            'name',
            'che_jian__name',
            'che_jian_id',
            'che_jian__phone',
            'phone')[0]
        watchkeeper = {
            'id': item.id,
            'name': user.name,
            'phone': user.phone,
            'gongQu': gong['name'],
            'gongQuId': gong['id'],
            'gongQuPhone': gong['phone'],
            'cheJianId': gong['che_jian_id'],
            'cheJian': gong['che_jian__name'],
            'cheJianPhone': gong['che_jian__phone']
        }
        watchkeepersJson.append(watchkeeper)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {
        'list': watchkeepersJson, 'length': len(watchkeeperList)}})


def listWatchkeeper(request):
    watchkeeperList = Watchkeeper.objects.all()
    watchkeepersJson = []
    for item in watchkeeperList:
        user = User.objects.get(id=item.user_id)
        gong = GongQu.objects.filter(id=int(user.gong_qu_id)).values(
            'id',
            'name',
            'che_jian__name',
            'che_jian_id',
            'che_jian__phone',
            'phone')[0]
        watchkeeper = {
            'id': user.id,
            'name': user.name,
            'phone': user.phone,
            'gongQu': gong['name'],
            'gongQuId': gong['id'],
            'gongQuPhone': gong['phone'],
            'cheJianId': gong['che_jian_id'],
            'cheJian': gong['che_jian__name'],
            'cheJianPhone': gong['che_jian__phone']
        }
        watchkeepersJson.append(watchkeeper)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {
        'list': watchkeepersJson}})


@csrf_exempt
def addEmphasisWork(request):
    context = request.POST['context']
    emphasis = EmphasisWork.objects.create(context=context)
    emphasis.save()
    if emphasis.id is None:
        return JsonResponse({"code": 500, 'message': '添加失败'})
    return JsonResponse({"code": 200, 'message': '添加成功'})


@csrf_exempt
def updateEmphasisWork(request):
    id = request.POST['id']
    context = request.POST['context']
    EmphasisWork.objects.filter(id=id).update(context=context)
    return JsonResponse({"code": 200, 'message': '修改成功'})


def deleteEmphasisWork(request):
    id = request.GET['id']
    try:
        EmphasisWork.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})

    return JsonResponse({"code": 200, "message": "删除成功"})


def pageEmphasisWork(request):
    limit = request.GET['limit']
    page = int(request.GET['page'])
    emphasisList = EmphasisWork.objects.filter()
    paginator = Paginator(emphasisList, limit)
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    emphasisJson = []
    for item in page:
        select = {'id': item.id, 'context': item.context}
        emphasisJson.append(select)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': emphasisJson, 'length': len(emphasisList)}})


def listEmphasisWork(request):
    emphasisList = EmphasisWork.objects.filter()
    emphasisJson = []
    for item in emphasisList:
        select = {'id': item.id, 'context': item.context}
        emphasisJson.append(select)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': emphasisJson}})


@csrf_exempt
def updateScrw(request):
    id = request.POST['id']
    gongQuId = request.POST['gongQuId']
    cheJianId = request.POST['cheJianId']
    xianMingId = request.POST['xianMingId']
    date = request.POST['date']
    workTypeId = request.POST['workTypeId']
    piZhunDate = request.POST['piZhunDate']
    geiDianDate = request.POST['geiDianDate']
    zuoYeDate = request.POST['zuoYeDate']
    fzrId = request.POST['fzrId']
    fhyId = request.POST['fhyId']
    llyId = request.POST['llyId']
    scxm = request.POST['scxm']
    wcqk = request.POST['wcqk']
    gznr = request.POST['gznr']
    czwt = request.POST['czwt']
    snzy = request.POST['snzy']
    Scrw.objects.filter(id=id).update(
        gong_qu_id=gongQuId,
        che_jian_id=cheJianId,
        xian_ming_id=xianMingId,
        date=date,
        work_type_id=workTypeId,
        pi_zhun_date=piZhunDate,
        gei_dian_date=geiDianDate,
        zuo_ye_date=zuoYeDate,
        fzr_id=fzrId,
        fhy_id=fhyId,
        lly_id=llyId,
        scxm=scxm,
        wcqk=wcqk,
        gznr=gznr,
        czwt=czwt,
        snzy=snzy
    )
    return JsonResponse({"code": 200, 'message': '修改成功'})


def deleteScrw(request):
    id = request.GET['id']
    try:
        Scrw.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})

    return JsonResponse({"code": 200, "message": "删除成功"})


def dataAnalysisByWeek(request):
    startTime = request.GET['startTime']
    endTime = request.GET['endTime']
    scrws = Scrw.objects.filter(date__gte=startTime, date__lte=endTime)
    return dataFx(scrws)


def dataAnalysisBySgjg(request):
    date = request.GET['date']
    date = date.split('-')
    works = WorkPlan.objects.filter(date__year=date[0], date__month=date[1], work_type=1)
    items = ["施工Ⅰ级", "施工Ⅱ级", "施工Ⅲ级", "邻近A", "邻近B", "邻近C"]
    data = [0, 0, 0, 0, 0, 0]
    for item in works:
        data[items.index(item.type)] += 1
    return JsonResponse({'code': 200, 'message': '查询成功', 'data': data})


def dataAnalysisByWxjh(request):
    date = request.GET['date']
    date = date.split('-')
    works = WorkPlan.objects.filter(date__year=date[0], date__month=date[1], work_type=2)
    items = ['Ⅰ级维修', 'Ⅱ级维修', '点外A类', '点外B类']
    data = [0, 0, 0, 0]
    for item in works:
        data[items.index(item.type)] += 1
    return JsonResponse({'code': 200, 'message': '查询成功', 'data': data})


def dataAnalysisByMouse(request):
    date = request.GET['date']
    year = date.split('-')[0]
    month = date.split('-')[1]
    scrws = Scrw.objects.filter(date__year=year, date__month=month)
    return dataFx(scrws)


def dataFx(scrws):
    cheJian = CheJian.objects.all()
    gongQu = GongQu.objects.all()
    dataItem = [[], [], [], []]
    for item in gongQu:
        dataItem[0].append(item.name)
        dataItem[1].append(item.id + 1024)
        dataItem[2].append(0)
        dataItem[3].append(0)
    for item in cheJian:
        dataItem[0].append(item.name)
        dataItem[1].append(item.id)
        dataItem[2].append(0)
        dataItem[3].append(0)
    for item in scrws:
        i = dataItem[1].index(item.gong_qu_id + 1024)
        dataItem[2][i] = dataItem[2][i] + 1
        if item.wcqk == 1:
            dataItem[3][i] = dataItem[3][i] + 1
        i = dataItem[1].index(item.che_jian_id)
        dataItem[2][i] = dataItem[2][i] + 1
        if item.wcqk == 1:
            dataItem[3][i] = dataItem[3][i] + 1
    return JsonResponse({'code': 200, 'message': '查询成功', 'data': dataItem})

